#include "pch.h"
#include "CTestComFactory.h"
#include "CTestCom.h"

ULONG CTestComFactory::g_objNum = 0;

CTestComFactory::CTestComFactory()
	: m_refNum(0)
{
	CTestComFactory::g_objNum++;
}

CTestComFactory::~CTestComFactory()
{
	CTestComFactory::g_objNum--;
}

ULONG __stdcall CTestComFactory::AddRef(void)
{
	return ++m_refNum;
}

ULONG __stdcall CTestComFactory::Release(void)
{
	--m_refNum;
	if (m_refNum == 0) {
		delete this;
		return 0;
	}
	return m_refNum;
}

HRESULT __stdcall CTestComFactory::QueryInterface(REFIID riid, void** ppvObject)
{
	if (riid == IID_IUnknown) {
		*ppvObject = static_cast<IUnknown*>(this);
		static_cast<IUnknown*>(this)->AddRef();
	}
	else if (riid == IID_IClassFactory) {
		*ppvObject = static_cast<IClassFactory*>(this);
		static_cast<CTestComFactory*>(this)->AddRef();
	}
	else {
		*ppvObject = NULL;
		return E_NOINTERFACE;
	}
	return S_OK;
}

HRESULT __stdcall CTestComFactory::CreateInstance(IUnknown* pUnkOuter, REFIID riid, void** ppvObject)
{
	if (pUnkOuter != NULL) {
		return CLASS_E_NOAGGREGATION;
	}
	HRESULT hres = E_OUTOFMEMORY;
	CTestCom* pObj = new CTestCom();
	if (pObj == NULL) {
		return hres;
	}
	hres = pObj->QueryInterface(riid, ppvObject);
	if (hres != S_OK) {
		delete pObj;
	}
	return hres;
}

HRESULT __stdcall CTestComFactory::LockServer(BOOL fLock)
{
	return E_NOTIMPL;
}
